package com.ilink.teacherservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkcommon.domain.PO.studyservice.UserCourseStudyStatus;
import com.ilink.ilinkcommon.domain.PO.trainingCamp.OfflineExport;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.domain.StatusEnum;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.teacherservice.mapper.OfflineExportMapper;
import com.ilink.teacherservice.mapper.UserCourseStudyStatusMapper;
import com.ilink.teacherservice.service.OfflineExportService;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import static com.ilink.ilinkcommon.domain.StatusEnum.COMPLETED;

/**
 * @author Black Curry
 * @description 针对表【offline_export(线下训练营名单导出表)】的数据库操作Service实现
 * @createDate 2024-10-08 11:04:11
 */
@Service
@Transactional
public class OfflineExportServiceImpl extends ServiceImpl<OfflineExportMapper, OfflineExport>
        implements OfflineExportService {

    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private UserCourseStudyStatusMapper userCourseStudyStatusMapper;

    /**
     * @return boolean
     * @Author Black Curry
     * @Description csv或者excel 导入线下数据库表接口 读取 csv 文件
     * @Date 14:14 2024/10/8
     * @Param []
     **/
    @Override
    public boolean importOfflineTable(MultipartFile csvFile) {
        try (Reader reader = new InputStreamReader(csvFile.getInputStream())) {
            CsvToBean<OfflineExport> csvToBean = new CsvToBeanBuilder<OfflineExport>(reader)
                    .withType(OfflineExport.class)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            List<OfflineExport> offlineExports = csvToBean.parse();
            //  对于已经存在的数据进行不覆盖，直接跳过
            offlineExports.forEach(offlineExport -> {
                LambdaQueryWrapper<OfflineExport> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OfflineExport::getSchoolId, offlineExport.getSchoolId())
                        .eq(OfflineExport::getCourseId, offlineExport.getCourseId())
                        .eq(OfflineExport::getCampId,
                                offlineExport.getCampId())
                        .eq(OfflineExport::getRealname, offlineExport.getRealname());
                if (this.count(queryWrapper) == 0) {
                    this.save(offlineExport);
                }
            });

            return true;
        } catch (Exception e) {
            log.error("导入线下名单信息错误", e);
            return false;
        }
    }

    /**
     * @return boolean
     * @Author Black Curry
     * @Description 同步线下名单中的学习状态到课程状态中 查询学习状态前需要先调用学习状态同步接口
     * @Date 14:15 2024/10/8
     * @Param [userId, courseId] 传递的是请求用户的账号id不是学号
     **/
    @Override
    public boolean syncCourseStudyStatus(User userDetail, String courseId) {
        try {
            // 依据 schoolId realname courseId 和 isSync 字段进行完成条件查询
            LambdaQueryWrapper<OfflineExport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OfflineExport::getSchoolId, userDetail.getSchoolId())
                    .eq(OfflineExport::getCourseId, Long.valueOf(courseId))
                    .eq(OfflineExport::getRealname, userDetail.getRealname())
                    .eq(OfflineExport::getIsSync, 0);

            // 查询出符合条件的数据
            List<OfflineExport> list = this.list(queryWrapper);
            if (list == null || list.isEmpty()) {
                //  找不到就不覆盖，认为是正确的，不需要再操作了
                return true;
            } else {
                if (list.size() > 1) {
                    //  找到多个数据，则出现问题
                    log.error("查询线下名单时找到多个数据，数据异常");
                    return false;
                } else {
                    //  找到一个数据，进行更新操作
                    OfflineExport offlineExport = list.get(0);
                    // 进行状态信息覆盖操作
                    // 目前只记录了用户对于课程某视频的学习状态，因此这里对每个课程相关的视频都进行覆盖
                    // 新增了对课程学习状态的记录表，直接覆盖整个课程的状态
//                    UserCourseStudyStatus userCourseStudyStatus = userCourseStudyStatusMapper.selectOne(new LambdaQueryWrapper<UserCourseStudyStatus>()
//                            .eq(UserCourseStudyStatus::getUserId, userId).eq(UserCourseStudyStatus::getCourseId, courseId).last("limit 1"));
//                    if (userCourseStudyStatus != null) {
//                        userCourseStudyStatus.setUserStudyStatus(2);
//
//                        System.out.println(userCourseStudyStatus);
//                        userCourseStudyStatusMapper.update(userCourseStudyStatus, new LambdaQueryWrapper<UserCourseStudyStatus>()
//                                .eq(UserCourseStudyStatus::getUserId, userId).eq(UserCourseStudyStatus::getCourseId, courseId));//.last("limit 1").last("limit 1")写法不正确
//                    }
                    UserCourseStudyStatus userCourseStudyStatus = userCourseStudyStatusMapper.selectOne(new LambdaQueryWrapper<UserCourseStudyStatus>()
                            .eq(UserCourseStudyStatus::getUserId, userDetail.getUserId()).eq(UserCourseStudyStatus::getCourseId, courseId).last("limit 1"));
                    if (userCourseStudyStatus != null) {
                        userCourseStudyStatus.setUserStudyStatus(StatusEnum.COMPLETED);
//                        int updateUserStudyStatus = userCourseStudyStatusMapper.updateUserStudyStatus(userCourseStudyStatus.getUserId(), userCourseStudyStatus.getCourseId(),  2);
                        int updateUserStudyStatus = userCourseStudyStatusMapper.update(userCourseStudyStatus, new LambdaQueryWrapper<UserCourseStudyStatus>()
                                .eq(UserCourseStudyStatus::getUserId, userDetail.getUserId()).eq(UserCourseStudyStatus::getCourseId, courseId));//.last("limit 1").last("limit 1")写法不正确

                        if (updateUserStudyStatus< 0) {
                            log.error( "更新用户学习状态失败");
                            return false;
                        }
//
                    }
                    else {
                        //没有记录则新增
                        userCourseStudyStatus = new UserCourseStudyStatus();
                        userCourseStudyStatus.setUserId(userDetail.getUserId());
                        userCourseStudyStatus.setCourseId(Long.valueOf(courseId));
                        userCourseStudyStatus.setUserStudyStatus(StatusEnum.COMPLETED);
                        userCourseStudyStatusMapper.insert(userCourseStudyStatus);
                    }
                    offlineExport.setIsSync(1);
                    this.updateById(offlineExport);
                    return true;
                }
            }
        }catch (Exception e) {
            log.error("同步线下学习状态失败", e);
            return false;
        }
    }


}




